%   filter3d 
%   Christopher J. Whalen
%   University of Illinois
%   04/25/05 - Date Created
%   04/25/05 - Last Modified


%   Purpose - to filter the MRI data set so as to remove graininess and
%   increase smoothness of the surface. Used prior to generation of the
%   segmented scalp. Uses 3 medfilt2 along 3 dimensions and then averages.



function [vol_avg] = filter3d(vol)


% fprintf('\n     filter3d\n');
% fprintf('Estimated Time To Filter: 0.4 min\n');
% tic;
dim = size(vol);
vol_axial = zeros(dim(1),dim(2),dim(3));
vol_sagittal = zeros(dim(1),dim(2),dim(3));
vol_coronal = zeros(dim(1),dim(2),dim(3));
vol_avg = zeros(dim(1),dim(2),dim(3));

% fprintf('Axial    Filtering...\n');
vol_axial = permute(vol_axial,[1 2 3]); % no need to permute axial
vol_filt = permute(vol,[1 2 3]); % no need to permute axial slices
for i_ax = 1:dim(3)
    %vol_axial(:,:,i_ax) = wiener2(vol_filt(:,:,i_ax));
    vol_axial(:,:,i_ax) = medfilt2(vol_filt(:,:,i_ax));
end

% fprintf('Sagittal Filtering...\n');
vol_sagittal = permute(vol_sagittal,[3 2 1]);
vol_filt = permute(vol,[3 2 1]); % permute the array so may filter along different direction
for i_sag = 1:dim(3)
    vol_sagittal(:,:,i_sag) = medfilt2(vol_filt(:,:,i_sag));
end
vol_sagittal = permute(vol_sagittal,[3 2 1]);

% fprintf('Coronal  Filtering...\n');
vol_coronal = permute(vol_coronal,[3 1 2]);
vol_filt = permute(vol,[3 1 2]);
for i_cor = 1:dim(3)
    vol_coronal(:,:,i_cor) = medfilt2(vol_filt(:,:,i_cor));
end
vol_coronal = permute(vol_coronal,[2 3 1]);

% fprintf('Averaging Filtered Data...\n');
vol_avg = (vol_axial + vol_sagittal + vol_coronal)/3;
% vol_avg = vol_axial;

clear vol_axial vol_sagittal vol_coronal vol_filt

% fprintf('Actual Time To Filter: %-2.1f min\n',toc/60);
% fprintf('   filter3d done\n\n');





